#region BSD License
/* 
Copyright (c) 2012, Marcio Rinaldi
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Marcio Rinaldi nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using EnvDTE;
using Microsoft.VisualStudio.TextTemplating;
using SmartStringResources.CodeDom;
using SmartStringResources.Dte;
using SmartStringResources.Properties.Strings;

namespace SmartStringResources
{
	public class SmartStringResourcesGenerator
	{
		private readonly ITextTemplatingEngineHost _t4Host;
		private readonly DTE _dte;
		private readonly IFileSystemService _fileSystemService;

		public SmartStringResourcesGenerator(ITextTemplatingEngineHost t4Host, DTE dte, IFileSystemService fileSystemService)
		{
			_t4Host = t4Host;
			_dte = dte;
			_fileSystemService = fileSystemService;
		}

		public static string Generate(object host, string templateFile, GeneratorOptions options = null)
		{
			return Generate(host, templateFile, new FileSystemService(), options);
		}

		public static string Generate(object host, string templateFile, IFileSystemService fileSystemService, GeneratorOptions options = null)
		{
			var serviceProvider = host as IServiceProvider;
			if (serviceProvider == null)
				return Resources.TemplateMustBeRunFromVisualStudio();

			var t4Host = host as ITextTemplatingEngineHost;
			if (t4Host == null)
				return Resources.TemplateMustBeRunFromVisualStudio();

			var dte = serviceProvider.GetService(typeof(DTE)) as DTE;
			if (dte == null)
				return Resources.TemplateMustBeRunFromVisualStudio();

			var generator = new SmartStringResourcesGenerator(t4Host, dte, fileSystemService);
			return generator.Generate(templateFile, options);
		}

		private string Generate(string templateFile, GeneratorOptions options)
		{
			var log = new StringBuilder();

			if (options == null)
				options = new GeneratorOptions();

			var resourceFile = GetResourcesFileName(templateFile);
			if (!_fileSystemService.Exists(resourceFile))
				return Resources.ResourceFileNotFound(fileName: Path.GetFileName(resourceFile));

			var project = _dte.GetProject();
			var templateProjectItem = project.GetProjectItemByFullPath(templateFile);
			log.AppendLine(Resources.ParentProjectItemFound(projectItem: templateProjectItem.Name));

			FixAccessibilityLevels(options, project, resourceFile);

			var codeDomProvider = CodeDomProvider.CreateProvider(project.GetLanguage());
			var codeFileName = codeDomProvider.GetCodeFileName(templateFile);
			var outputFileName = GetOutputFileName(templateFile);

			DeleteUnknownDependentProjectItems(codeFileName, outputFileName, templateProjectItem);
		    CheckoutFile(codeFileName);

			using (var generatedFile = _fileSystemService.GetStreamWriter(codeFileName, FileMode.Create))
			{
				templateProjectItem.ProjectItems.AddFromFile(codeFileName);
			    var codeGenerator = new CodeGenerator(codeDomProvider, _fileSystemService);
			    generatedFile.Write(codeGenerator.GenerateContents(project, resourceFile, options));
			}

			return log.ToString();
		}

	    private void FixAccessibilityLevels(GeneratorOptions options, Project project, string resourceFile)
	    {
	        if (options.ResourcesAccessibilityLevel == AccessibilityLevel.Default || options.ResourceKeysAccessibilityLevel == AccessibilityLevel.Default)
	        {
	            var resourceAccessibilityLevel = GetAccessibilityLevel(project, resourceFile);
	            if (options.ResourcesAccessibilityLevel == AccessibilityLevel.Default)
	                options.ResourcesAccessibilityLevel = resourceAccessibilityLevel;

	            if (options.ResourceKeysAccessibilityLevel == AccessibilityLevel.Default)
	                options.ResourceKeysAccessibilityLevel = resourceAccessibilityLevel;
	        }
	    }

	    private void DeleteUnknownDependentProjectItems(string codeFileName, string outputFileName, ProjectItem templateProjectItem)
	    {
	        var fileNames = new[] {codeFileName, outputFileName};

	        foreach (var projectItem in templateProjectItem.ProjectItems.OfType<ProjectItem>().Where(pi => !fileNames.Contains(pi.FileNames[0])))
	            DeleteProjectItem(projectItem);
	    }

	    private void DeleteProjectItem(ProjectItem projectItem)
		{
			for (short i = 0; i < projectItem.FileCount; i++)
			{
				var fileName = projectItem.FileNames[i];
				CheckoutFile(fileName);
			}
			projectItem.Delete();
		}

		private void CheckoutFile(string fileName)
		{
			var sourceControl = _dte.SourceControl;
			if (sourceControl.IsItemUnderSCC(fileName) && !sourceControl.IsItemCheckedOut(fileName))
				sourceControl.CheckOutItem(fileName);
		}

		private string GetOutputFileName(string templateFile)
		{
			_t4Host.SetFileExtension(".txt");
			return Path.ChangeExtension(templateFile, "txt");
		}

		private AccessibilityLevel GetAccessibilityLevel(Project project, string resourceFile)
		{
			var projectItem = project.GetProjectItemByFullPath(resourceFile);
			var customTool = projectItem.GetCustomTool();

			if (customTool != null && customTool.Contains("Public"))
				return AccessibilityLevel.Public;

			return AccessibilityLevel.Internal;
		}

		private string GetResourcesFileName(string templateFile)
		{
			return Path.ChangeExtension(templateFile, "resx");
		}
	}
}